<template>
    <a-layout style="min-height: 100vh">
        <a-layout-header style="background: var(--body-background); padding: 0 20px">
            <a-row>
                <a-col :span="12">
                    <h1>Low Code by Aqi</h1>
                </a-col>
                <a-col :span="12" style="text-align: right">
                    <a-space>
                        <a-button @click="showJson = true">生成JSON</a-button>
                        <a-button type="primary" @click="previewVisible = true">
                            预览
                        </a-button>
                    </a-space>
                </a-col>
            </a-row>
        </a-layout-header>
        <a-layout style="margin-top: 3px">
            <sider :treeData="treeData" :golbal="golbal" :width="visibleComponent ? 440 : 50" />

            <a-layout-content id="LayoutContent" style="
                    position: relative;
                    height: calc(100vh - 70px);
                    overflow-y: auto;
                    overflow-x: hidden;
                    padding: 5px;
                ">
                <ml-render :treeData="treeData" :golbal="golbal" :list="treeData" />
            </a-layout-content>
            <a-layout-sider style="
                    background: var(--body-background);
                    border-left: 2px solid #ccc;
                    padding: 0 5px;
                " :width="right_width">
                <tab-option> </tab-option>
            </a-layout-sider>
        </a-layout>
        <JSON-view v-model:visible="showJson" width="50vw" />
        <a-modal title="预览" v-model:visible="previewVisible" width="100%" wrap-class-name="full-modal" :footer="null"
            :bodyStyle="{ minHeight: 'cacl(100vh - 55px)', overflow: 'auto' }">
            <ml-preview v-if="previewVisible" :treeData="result" :golbal="golbal"></ml-preview>
        </a-modal>
    </a-layout>
</template>

<script lang="ts">
import MlRender from "./ml-render/render-v1.1/index.vue";
import TabOption from "./tab-option/index.vue";
import JSONView from "./JSON-view/index.vue";
import MlPreview from "./ml-render/preview-v1.1/index.vue";
import Sider from "./sider/index.vue";

import { ref, defineComponent, onMounted, watch, provide, computed } from "vue";
import { cloneDeep } from "lodash-es";
import treeDataSources from "./data/tree.json";
import temDrawer from "./data/drawer.json";
import { insertTree } from "./ml-render/hook/comon";
import api from "@/api/index";
import { ComponentType } from "@/type/components/index";
import { NodeAttrType } from "./type";

// 数据格式化
function mapComponent(component: ComponentType): NodeAttrType {
    let data = cloneDeep(component);
    const attributes: any = {};
    component.attributes.forEach((a) => {
        try {
            const val = JSON.parse(a.defaultValue);

            if (Array.isArray(val)) {
                attributes[a.attributeValue] = val[0].value;
            } else {
                attributes[a.attributeValue] = val;
            }
        } catch (e) {
            if (a.dataType == "SelectOption") {
                attributes[a.attributeValue] = [];
            } else {
                attributes[a.attributeValue] = "";
            }
        }
    });

    return {
        ...data,
        attributes,
        children: data.label ? null : [],
    };
}

export default defineComponent({
    components: {
        MlRender,
        TabOption,
        JSONView,
        MlPreview,
        Sider,
    },
    setup() {
        const golbal = ref<any>({
            $api: api,
            dataSource: [],
            columns: [],
            event: [
                {
                    name: "func_12351521",
                    func: "this.visible = true; this.current = arguments[0];",
                },
                {
                    name: "asdfn123",
                    func: `
                    this.$api.post('/update',this.form).then(res => {
                        this.$testRef.reload()
                    })`,
                },
                {
                    name: "vbmmgms",
                    func: "this.visible = false;",
                },
            ],
        });

        const visible = ref(false);
        const current = ref(null);

        provide(
            "current",
            computed({
                get: () => current.value,
                set: (val) => (current.value = val),
            })
        );

        const treeData = ref(insertTree(treeDataSources, temDrawer));

        provide(
            "treeData",
            computed(() => treeData.value)
        );

        watch(
            () => golbal.value,
            (val) => {
                // console.log(val);
            },
            {
                deep: true,
            }
        );

        const showJson = ref(false);
        const previewVisible = ref(false);
        const result = computed(() => cloneDeep(treeData.value));

        const hoverActive = ref();
        provide(
            "hoverActive",
            computed({
                get: () => hoverActive.value,
                set: (val) => (hoverActive.value = val),
            })
        );

        provide(
            "golbal",
            computed(() => golbal.value)
        );

        // 右宽度
        const right_width = ref<number>(350);
        // 组件库弹窗
        const visibleComponent = ref(false);
        provide(
            "visibleComponent",
            computed({
                get: () => visibleComponent.value,
                set: (val) => {
                    right_width.value = val ? 0 : 350;
                    visibleComponent.value = val;
                },
            })
        );

        // 被拖拽cur
        const cur_drag = ref<ComponentType | undefined>();
        // 处理拖拽方法
        const handleSelectStart = (row: ComponentType) => {
            cur_drag.value = row;
        };
        provide("handleSelectStart", handleSelectStart);
        // 拖拽放置方法
        const handleDrop = (row: NodeAttrType) => {
            if (cur_drag.value) {
                let mapData: NodeAttrType = mapComponent(cur_drag.value);
                row.children?.push(mapData);
            }
        };
        provide("handleDrop", handleDrop);

        const componnetsData = ref([]);
        const onLoadData = async () => {
            // let res = await request.get("/compont/list");
            // componnetsData.value = res.data;
            let res = await import("./data/components.json");
            componnetsData.value = res.data;
        };
        provide(
            "componnetsData",
            computed(() => componnetsData.value)
        );

        onMounted(() => {
            golbal.value["dataSource"] = [
                {
                    name: "测试人工-1",
                    age: "18",
                },
                {
                    name: "测试人工-1",
                    age: "18",
                },
                {
                    name: "测试人工-1",
                    age: "18",
                },
                {
                    name: "测试人工-1",
                    age: "18",
                },
                {
                    name: "测试人工-1",
                    age: "18",
                },
                {
                    name: "测试人工-1",
                    age: "18",
                },
            ];

            golbal.value["columns"] = [
                {
                    key: "test-0",
                    title: "姓名",
                    dataIndex: "name",
                    isSearch: true,
                    type: "string",
                },
                {
                    key: "test-1",
                    title: "年龄",
                    dataIndex: "age",
                    isSearch: true,
                    type: "Array",
                    options: [
                        {
                            label: "测试",
                            value: 1,
                        },
                    ],
                },
                {
                    key: "test-2",
                    title: "性别",
                    dataIndex: "sex",
                    isSearch: true,
                    type: "string",
                },
                {
                    key: "action",
                    title: "操作",
                    width: 200,
                },
            ];

            onLoadData();
        });

        return {
            treeData,
            golbal,
            visible,
            current,
            showJson,
            previewVisible,
            result,
            hoverActive,

            visibleComponent,
            right_width,
        };
    },
});
</script>
